package com.egoo.ticket.server.project.jincheng;

import com.egoo.ticket.server.dao.TaskTimeOutRecordDao;
import com.egoo.ticket.server.dao.WorkOrderTypeNodeDao;
import com.egoo.ticket.server.pojo.entity.WorkOrder;
import com.egoo.ticket.server.pojo.vo.TaskTimeOutRecordVo;
import com.egoo.ticket.server.pojo.vo.WorkOrderTypeNodeVo;
import com.egoo.ticket.server.service.EripDataSynService;
import com.egoo.ticket.server.service.EurmDataSyncService;
import com.egoo.ticket.server.utils.common.ConstantCode;
import com.egoo.ticket.server.utils.common.DateHandleUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Auther: victor_tang
 * @Date: 2020/10/15 16:30
 * @Description:
 */
@Component
@Slf4j
public class JinchengTimeOutJudge {
	@Autowired
	private WorkOrderTypeNodeDao workOrderTypeNodeDao;
	@Value("${server.work-time}")
	private String workTime;
	public static SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
	@Autowired
	private EripDataSynService eripDataSynService;
	@Autowired
	private EurmDataSyncService eurmDataSyncService;
	@Autowired
	private TaskTimeOutRecordDao taskTimeOutRecordDao;
	/*******************************************************/
	/**
	 * @Author: Donny_dong
	 * @Description: 锦城超时处理
	 * @Param:
	 * @return:
	 * @Date: 2020/8/19
	 */
	public Boolean handleTimeOutForJinCheng(TaskTimeOutRecordVo taskTimeOutRecordVo, WorkOrder workOrder) {
//		节点设置的时间毫秒值
		Long nodeSetTime = getNodeSetTime(taskTimeOutRecordVo);
		if (nodeSetTime == null) {
			log.info("节点不存在，不进行超时统计");
			return false;
		}
//		if (nodeSetTime == 0) {
//			log.info("节点配置时间为0，直接超时");
//			return true;
//		}
//		获取休息日
		List<Integer> moreYear = getMoreYear();
		List<String> restDateList = new ArrayList<>();
		for (Integer year:moreYear
			 ) {
			List<String> dateList = eurmDataSyncService.getRestDay(year);
			restDateList.addAll(dateList);
		}
		log.info("获取节假日："+restDateList);
		if (CollectionUtils.isEmpty(restDateList)){
			log.info("获取的节假日信息为空,不进行超时统计");
			return false;
		}
//		List<String> restDateList = new ArrayList<>();
//		工作日列表
		List<String> workDayList = getWorkDay(restDateList);
//		工作时间
		List<String> workTimeList = getWorkTime();
		Date startTime = taskTimeOutRecordVo.getStartTime();
		String startTimeStr = sdfDate.format(startTime);
		if (workDayList.contains(startTimeStr)) {
			return handleWorkDayTask(startTime, workDayList, workTimeList, nodeSetTime);
		} else {
			Date workDayStartTime = nonWorkTaskTimeToWorkDayTime(startTimeStr, restDateList, workTimeList);
			if (workDayStartTime != null) {
				return handleWorkDayTask(workDayStartTime, workDayList, workTimeList, nodeSetTime);
			} else {
				return false;
			}
		}

	}

	/**
	 * @Author: Donny_dong
	 * @Description: 获取超时记录表中的年份
	 * @Param:
	 * @return:
	 * @Date: 2021/1/5
	 */
	public  List<Integer> getMoreYear() {
		List<Integer> yearList = taskTimeOutRecordDao.selectYear();
//		List<Integer> yearList =null;
		List<Integer> list = new ArrayList<>();
		if (CollectionUtils.isEmpty(yearList)){
			LocalDate now = LocalDate.now();
			int year = now.getYear();
			list.add(year);
			return list;
		}

		return yearList;

	}

	/**
	 * @Author: Donny_dong
	 * @Description: 工作日内的任务超时
	 * @Param:
	 * @return:
	 * @Date: 2020/8/20
	 */
	private Boolean handleWorkDayTask(Date startTime, List<String> workDayList, List<String> workTimeList, Long nodeSetTime) {
		String workDay = sdfDate.format(startTime);
		String endWorkTimeStr = null;
		endWorkTimeStr = workTimeList.get(1);
		String endWorkDateStr = workDay + " " + endWorkTimeStr;
		Long endWorkTimeMils = DateHandleUtil.getTimeByDateStr(endWorkDateStr);
		long startTaskTimeMils = startTime.getTime();
		try {
			return workTimeTaskHandle(startTaskTimeMils, endWorkTimeMils, workDay, workDayList, workTimeList, nodeSetTime);
		} catch (Exception e) {
			log.info("任务超时处理异常" + e);
			return false;
		}
	}
	/**
	 * @Author: Donny_dong
	 * @Description: 工作时间段内任务超时
	 * @Param:
	 * @return:
	 * @Date: 2020/8/20
	 */
	private Boolean workTimeTaskHandle(long startTaskTimeMils, Long endWorkTimeMils, String workDay, List<String> workDayList, List<String> workTimeList, Long nodeSetTime) {
		try {
			long timeOutPoint = startTaskTimeMils + nodeSetTime;
			if (timeOutPoint <= endWorkTimeMils) {
				long currentTimeMillis = System.currentTimeMillis();
				if (currentTimeMillis > timeOutPoint) {
					return true;
				} else {
					return false;
				}
			} else {
				long usedTimeMils = endWorkTimeMils - startTaskTimeMils;
				long requestTimeMils = 0;
				if (usedTimeMils >= 0) {
					requestTimeMils = nodeSetTime - usedTimeMils;
				} else {
					requestTimeMils = nodeSetTime;
				}
				int nextDay = workDayList.indexOf(workDay) + 1;
				String nextWorkDay = workDayList.get(nextDay);
				String startWorkTimeStr = null;
				startWorkTimeStr = workTimeList.get(0);
				String nextStartWorkTimeDate = nextWorkDay + " " + startWorkTimeStr;
				Date nextStartDateTime = new Date(DateHandleUtil.getTimeByDateStr(nextStartWorkTimeDate));
				return this.handleWorkDayTask(nextStartDateTime, workDayList, workTimeList, requestTimeMils);

			}
		} catch (Exception e) {
			log.info("工作时间内的任务超时处理异常" + e);
		}
		return false;
	}
	/**
	 * @Author: Donny_dong
	 * @Description: 非工作的任务时间转换为下一个工日的开始时间
	 * @Param:
	 * @return:
	 * @Date: 2020/8/20
	 */
	private Date nonWorkTaskTimeToWorkDayTime(String startTimeStr, List<String> restDateList, List<String> workTimeList) {
		try {
			int currentDayIndex = restDateList.indexOf(startTimeStr);
			int nextDayIndex = currentDayIndex + 1;
			String workDayStartTimeStr = workTimeList.get(0);
			String workDay = null;
			if (nextDayIndex == restDateList.size()) {
				workDay = getWorkDayStartTime(startTimeStr);
				Date workDayStartTime = getWorkDayStartDateTime(workDay, workDayStartTimeStr);
				return workDayStartTime;
			}

			for (int i = currentDayIndex; i < restDateList.size(); i++) {
				workDay = getWorkDayStartTime(restDateList.get(i));
				if (restDateList.contains(workDay)) {
					continue;
				}
				Date workDayStartTime = getWorkDayStartDateTime(workDay, workDayStartTimeStr);
				return workDayStartTime;
			}
		} catch (Exception e) {
			log.info("非工作的任务时间转换为下一个工日的开始时间异常" + e);
		}
		return null;
	}
	/**
	 * @Author: Donny_dong
	 * @Description: 获取休息日的下一工作日的开始时间
	 * @Param:
	 * @return:
	 * @Date: 2020/8/20
	 */
	private Date getWorkDayStartDateTime(String workDay, String workDayStartTimeStr) {
		String workDayStartDateTimeStr = workDay + " "+workDayStartTimeStr;
		Date workDayStartTime = new Date(DateHandleUtil.getTimeByDateStr(workDayStartDateTimeStr));
		return workDayStartTime;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 获取非工作的下一个工作日
	 * @Param:
	 * @return:
	 * @Date: 2020/8/20
	 */
	private String getWorkDayStartTime(String startTimeStr) {
		try {
			Date tmpDate = sdfDate.parse(startTimeStr);

			Calendar cld = Calendar.getInstance();
			cld.setTime(tmpDate);
			cld.add(Calendar.DATE, 1);

			return sdfDate.format(cld.getTime());
		} catch (ParseException e) {
			log.info("获取下一个日期日期转换异常" + e);
			return null;
		}
	}
	/**
	 * @Author: Donny_dong
	 * @Description: 获取工作日
	 * @Param:
	 * @return:
	 * @Date: 2020/8/20
	 */
	private List<String> getWorkDay(List<String> restDateList) {
		List<Integer> moreYear = this.getMoreYear();
		// 获取当前年的所有日期
		List<String> allYearDateList = DateHandleUtil.getYearAllDate(moreYear);
		if (!CollectionUtils.isEmpty(restDateList)) {
			allYearDateList.removeAll(restDateList);
		}
		return allYearDateList;
	}


	/**
	 * @Author: Donny_dong
	 * @Description: 获取节点设置时间毫秒值
	 * @Param:
	 * @return:
	 * @Date: 2020/8/20
	 */
	private Long getNodeSetTime(TaskTimeOutRecordVo taskTimeOutRecordVo) {
		String nodeId = taskTimeOutRecordVo.getNodeId();
		if (StringUtils.isEmpty(nodeId)) {
			return null;
		}
		WorkOrderTypeNodeVo workOrderTypeNodeVo = workOrderTypeNodeDao.getNodeByWorkOrderNodeId(Long.valueOf(nodeId));
		Double dealTime = workOrderTypeNodeVo.getContent().getDouble("dealtime");
		if (dealTime == null) {
			return 0L;
		}
		Double dealTimeDou = dealTime * 60 * 60 * 1000;
		long dealTimeLong = dealTimeDou.longValue();
		return dealTimeLong;
	}
	/**
	 * @Author: Donny_dong
	 * @Description: 获取工作时间
	 * @Param:
	 * @return:
	 * @Date: 2020/8/20
	 */
	private List<String> getWorkTime() {
//		List<String> workTimeList = eripDataSynService.getWorkTimeList();
		List<String> workTimeList = new ArrayList<>();
		String[] split = workTime.split("-");
		String startTime = split[0];
		String endTime = split[1];
		workTimeList.add(startTime);
		workTimeList.add(endTime);
		if (CollectionUtils.isEmpty(workTimeList)) {
			workTimeList.add(ConstantCode.DefaultWorkTime.START_TIME);
			workTimeList.add(ConstantCode.DefaultWorkTime.END_TIME);
		}
		return workTimeList;
	}

}
